// Simple in-memory sliding window rate limiter per IP and route
// Not suitable for multi-process or distributed runs

const WINDOW_MS = 60 * 1000; // 1 minute
const MAX_REQUESTS = 120; // per window per IP per route

const ipRouteToHits = new Map();

function cleanupOld(now) {
    for (const [key, hits] of ipRouteToHits.entries()) {
        const recent = hits.filter((ts) => now - ts <= WINDOW_MS);
        if (recent.length === 0) {
            ipRouteToHits.delete(key);
        } else {
            ipRouteToHits.set(key, recent);
        }
    }
}

function rateLimiter(req, res, next) {
    const now = Date.now();
    const ip = req.ip || req.connection?.remoteAddress || 'unknown';
    const routeKey = `${ip}:${req.baseUrl}${req.path}`;
    const hits = ipRouteToHits.get(routeKey) || [];
    const recent = hits.filter((ts) => now - ts <= WINDOW_MS);
    recent.push(now);
    ipRouteToHits.set(routeKey, recent);

    if (recent.length > MAX_REQUESTS) {
        res.setHeader('Retry-After', Math.ceil(WINDOW_MS / 1000));
        return res.status(429).json({ error: 'rate_limited' });
    }

    if (Math.random() < 0.02) cleanupOld(now); // opportunistic cleanup

    return next();
}

module.exports = { rateLimiter };


